package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.commons.templates.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.NearUserVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.RecommendQueryVo;
import com.tanhua.domain.vo.TodayBestVo;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 今日佳人业务层
 */
@Service
public class TodayBestService {

    @Reference
    private RecommendUserApi recommendUserApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private QuestionApi questionApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Reference
    private UserLocationApi userLocationApi;

    /**
     * 接口名称：今日佳人
     */
    public ResponseEntity<Object> queryTodayBest() {
        // 1.获取当前登录用户id
        Long userId = UserHolder.getUserId();

        // 2.调用服务提供者api查询用户的今日佳人
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);

        if (recommendUser == null) {
            // 如果没有推荐用户，设置默认数据
            recommendUser = new RecommendUser();
            recommendUser.setUserId(userId);
            recommendUser.setRecommendUserId(20l);
            recommendUser.setScore(99d);
        }

        // 3.封装返回结果
        TodayBestVo vo = new TodayBestVo();

        // 3.1 查询今日佳人的用户详情
        UserInfo userInfo = userInfoApi.findById(recommendUser.getRecommendUserId());
        if (userInfo != null) {
            BeanUtils.copyProperties(userInfo, vo);
            // 转换标签
            if (!StringUtils.isEmpty(userInfo.getTags())) {
                String[] tags = userInfo.getTags().split(",");
                vo.setTags(tags);
            }
        }

        // 3.2 设置缘分值
        vo.setFateValue(recommendUser.getScore().longValue());

        return ResponseEntity.ok(vo);
    }

    /**
     * 接口名称：推荐朋友
     */
    public ResponseEntity<Object> queryRecommendation(RecommendQueryVo param) {
        // 1.获取当前登录用户id
        Long userId = UserHolder.getUserId();

        // 2.调用服务提供者api查询推荐用户列表
        PageResult pageResult = recommendUserApi.queryRecommendation(userId, param.getPage(), param.getPagesize());

        // 获取当前页数据
        List<RecommendUser> items = (List<RecommendUser>) pageResult.getItems();

        if (items == null) {
            // 如果没有推荐数据，设置默认数据
            items = new ArrayList<>();
            for (long i = 5; i < 10; i++) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setRecommendUserId(i);
                recommendUser.setScore(70d + i);
                items.add(recommendUser);
            }
        }

        // 3.封装返回结果
        List<TodayBestVo> voList = new ArrayList<>();

        for (RecommendUser recommendUser : items) {

            // 3.1 创建vo
            TodayBestVo vo = new TodayBestVo();

            // 3.1 查询推荐用户详情
            UserInfo userInfo = userInfoApi.findById(recommendUser.getRecommendUserId());

            if (userInfo != null) {
                BeanUtils.copyProperties(userInfo, vo);
                // 转换标签
                if (!StringUtils.isEmpty(userInfo.getTags())) {
                    String[] tags = userInfo.getTags().split(",");
                    vo.setTags(tags);
                }
            }

            // 3.3 设置缘分值
            vo.setFateValue(recommendUser.getScore().longValue());

            // 3.4 把vo添加到voList
            voList.add(vo);
        }


        // 4.重新设置items的值
        pageResult.setItems(voList);

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：佳人信息
     */
    public ResponseEntity<Object> queryPersonalInfo(Long id) {
        // 1.调用服务提供者api查询用户详情
        UserInfo userInfo = userInfoApi.findById(id);

        // 2.封装返回结果
        TodayBestVo vo = new TodayBestVo();
        BeanUtils.copyProperties(userInfo, vo);

        if (userInfo.getTags() != null) {
            vo.setTags(userInfo.getTags().split(","));
        }
        // 当前登录用户和佳人的缘分值
        Long score = recommendUserApi.queryScore(UserHolder.getUserId(), id);
        vo.setFateValue(score);

        return ResponseEntity.ok(vo);
    }

    /**
     * 接口名称：查询陌生人问题
     */
    public ResponseEntity<Object> strangerQuestions(Long userId) {
        // 1.根据用户id查询陌生人问题
        Question question = questionApi.findByUserId(userId);

        String content = "";

        if (question == null) {
            content = "你真的爱我吗？";
        } else {
            content = question.getTxt();
        }

        return ResponseEntity.ok(content);
    }

    /**
     * 接口名称：回复陌生人问题
     */
    public ResponseEntity<Object> replyQuestions(Long userId, String reply) {

        // 封装消息内容
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", UserHolder.getUserId()); // 发送者的id
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());
        msg.put("nickname", userInfo.getNickname()); // 发送者的昵称

        // 查询目标用户的陌生人问题
        Question question = questionApi.findByUserId(userId);
        String content = (question == null ? "你喜欢什么？" : question.getTxt());
        msg.put("strangerQuestion", content);
        msg.put("reply", reply);

        // 调用环信api发送陌生人消息，参数1-目标用户id，参数2-消息json字符串
        huanXinTemplate.sendMsg(userId.toString(), JSON.toJSONString(msg));

        return ResponseEntity.ok(null);
    }

    /**
     * 接口名称：搜附近
     */
    public ResponseEntity<Object> searchNear(String gender, Integer distance) {
        // 1.调用服务提供者api查询附近的人id集合
        List<Long> userIdList = userLocationApi.searchNear(UserHolder.getUserId(), distance);

        // 2.根据用户id集合查询用户详情集合，过滤性别，排除自己
        if (userIdList != null) {
            List<UserInfo> userInfoList = userInfoApi.findByIdList(userIdList, gender, UserHolder.getUserId());

            // 3.封装返回结果
            List<NearUserVo> voList = new ArrayList<>();

            for (UserInfo userInfo : userInfoList) {
                // 3.1 创建vo
                NearUserVo vo = new NearUserVo();
                vo.setUserId(userInfo.getId());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());

                // 3.2 添加vo
                voList.add(vo);
            }
            return ResponseEntity.ok(voList);
        }

        return ResponseEntity.ok(null);
    }
}
